﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Forest.Cat.Domain;
using Forest.Cat.Domain.Entities;
using System.Web;
using Forest.Cat.Domain.Services.Authentication;
using Forest.Cat.Domain.Services.Jobseekers;

namespace Forest.Web.Framework {
    public class WorkContext : IWorkContext {

        private readonly HttpContextBase _httpContext;
        private readonly IAuthenticationService _authenticationService;
        private readonly IJobseekerService _jobseekerService;

        private Jobseeker _cachedJobseeker;
        private bool _cachedIsAdmin;

        public WorkContext(HttpContextBase httpContext,
             IAuthenticationService authenticationService,
            IJobseekerService jobseekerService) {
            this._httpContext = httpContext;
            this._authenticationService = authenticationService;
            this._jobseekerService = jobseekerService;
        }

        public Jobseeker CurrentUser {
            get { return GetCurrentUser(); }
            set { _cachedJobseeker = value; }
        }

        private Jobseeker GetCurrentUser() {

            if (_cachedJobseeker != null)
                return _cachedJobseeker;

            Jobseeker jobseeker= null;
            if (_httpContext != null) {
                //registered user
                if (jobseeker == null) {
                    jobseeker = _authenticationService.GetAuthenticatedUser();
                }

                // Validation
                if (jobseeker != null) {
                    // update last activity date
                    jobseeker.LastSignedIn = DateTime.Now;
                    _jobseekerService.UpdateUser(jobseeker);
                }

                _cachedJobseeker = jobseeker;
                    
            }

            return _cachedJobseeker;
            
        }
        public bool IsAdmin {
            get { return _cachedIsAdmin; }
            set { _cachedIsAdmin = value; }
        }

    }
}
